package com.rogers.monster.auth;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class LoginBean {

    // properties
    private String userId = " ";

    private String password;

    private AuthenticationManager authenticationManager;
    
    
    
    public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

	/**
     * default empty constructor
     */
    public LoginBean() {

        Exception ex = (Exception) FacesContext
                .getCurrentInstance()
                .getExternalContext()
                .getSessionMap()
                .get(AbstractAuthenticationProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);

        if (ex != null)
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_ERROR, ex
                            .getMessage(), ex.getMessage()));

    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId.trim();
    }

    
   
    
    public void login(ActionEvent e) throws IOException  {
    	
    	FacesContext context = FacesContext.getCurrentInstance();
    	ExternalContext ec = context.getExternalContext();
    	
    		try {
				Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
				UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(userId, password);
				authToken.setDetails(authentication.getDetails());

				
				
				((HttpServletRequest) ec.getRequest()).getSession().setAttribute(
						UsernamePasswordAuthenticationFilter.SPRING_SECURITY_LAST_USERNAME_KEY, authToken.getName());

				Authentication newAuth = authenticationManager.authenticate(authToken);
				SecurityContextHolder.getContext().setAuthentication(newAuth);		
				String encodedURL = ec.encodeResourceURL(ec.getRequestContextPath() + "/secured/welcome.jspx");
		    	((HttpServletResponse) ec.getResponse()).sendRedirect(encodedURL);

				
			} catch (AuthenticationException e1) {
				FacesContext.getCurrentInstance().addMessage(null,
	    				new FacesMessage(FacesMessage.SEVERITY_ERROR, e1.getMessage(), e1.getMessage()));
			}

    	//ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    	
    }


}